Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

386
Visualizações
React: What is the difference between const newArray = oldArray and const newArray = [...oldArray]

I have a piece of code in React, where if I use newArray = [... oldArray] it works, but if I use newArray = oldArray it doesn't. Can you tell me why?

Below the code. It's about adding a todo list when you click the Add button. So far it works. Then when you click on an item on the todo list, it should change class and become 'highlighted'. If I use newArray = oldArray, the state is correctly updated but then nothing changes on the screen:

const Todo = () => {
  const [item, setItem] = useState('');
  const [itemList, setItemList] = useState([]);

  const onChange = (e) => {
    setItem(e.target.value);
  };

  const handleClick = () => {
    setItemList((prevState) => [
      ...prevState,
      { id: Math.random(), item: item, isDone: false },
    ]);
    setItem('');
  };

  const handleItemClass = (i) => {
    const updatedItemList = itemList;
    updatedItemList[i].isDone = !updatedItemList[i].isDone;
    setItemList(updatedItemList);
  };

  return (
    <React.Fragment>
      <div>
        <input type="text" onChange={onChange} value={item} />
        <button onClick={handleClick}>Add</button>
      </div>
      <p>
        {itemList.filter((el) => el.isDone).length} completed from{' '}
        {itemList.length}
      </p>
      <ul>
        {itemList.map((itemCurrent, i) => (
          <li
            key={itemCurrent.id}
            onClick={() => handleItemClass(i)}
            className={itemCurrent.isDone ? 'is-done' : 'not-done'}
          >
            {itemCurrent.item}
          </li>
        ))}
      </ul>
    </React.Fragment>
  );
};
export default Todo;

render(<Todo />, document.getElementById('root'));
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda